import 'package:flutter_douban/model/cook_info_model.dart';
import 'package:sqflite/sqlite_api.dart';
import 'base_db_provider.dart';

class CookDbProvider extends BaseDbProvider {
  /// 表名
  final String name = 'CookInfoTable';

  /// 做饭id
  final String Id = "id";

  /// 图片链接
  final String img = "img";

  /// 做饭描述
  final String n = "n";

  /// 用户名字
  final String nickName = "nickName";

  /// 用户头像
  final String nickIcon = "nickIcon";

  /// 收藏用户电话
  final String phoneNum = "phoneNum";

  /// 收藏时间
  final String time = "time";

  /// 视频播放url
  final String videoUrl = "videoUrl";

  CookDbProvider();
  @override
  tableName() {
    return name;
  }

  /// 创建表
  @override
  createTableString() {
    return '''
        create table $name (
    $Id integer primary key,$img text not null,$n text not null,$nickName text not null,$nickIcon text not null,$phoneNum text not null,$time bigint,$videoUrl text not null)
     ''';
  }

  /// 查询数据库
  Future _getCookProvider(Database db, int id, String phone) async {
    List<Map<String, dynamic>> maps = await db
        .rawQuery("select * from $name where $Id = $id AND $phoneNum = $phone");
    return maps;
  }

  /// 插入到数据库
  Future insert(CookInfoModel model, String phone) async {
    Database db = await getDataBase();
    var noteProvider = await _getCookProvider(db, model.id!, phone);
    if (noteProvider != null) {
      /// 删除数据
      await db.delete(name,
          where: "$Id = ? AND $phoneNum = ?", whereArgs: [model.id, phone]);
    }

    ///   Id img n nickName nickIcon phoneNum creatTime
    return await db.rawInsert(
        "insert into $name ($Id,$img,$n,$nickName,$nickIcon,$phoneNum,$time,$videoUrl) values (?,?,?,?,?,?,?,?)",
        [
          model.id,
          model.img,
          model.n,
          model.a!.n,
          model.a!.p,
          phone,
          /// 当前时间戳
          DateTime.now().millisecondsSinceEpoch,
          model.vfurl==null?'':model.vfurl,
        ]);
  }

  /// 删除到数据库
  Future delete(int id, String phone) async {
    Database db = await getDataBase();
    var noteProvider = await _getCookProvider(db, id, phone);
    if (noteProvider != null) {
      /// 删除数据
      await db.delete(name,
          where: "$Id = ? AND $phoneNum = ?", whereArgs: [id, phone]);
    }
    return await db.rawDelete(
      "delete from $name where $Id = $id AND $phoneNum = $phone",
    );
  }

  /// 获取表中符合用户的全部数据
  Future<List<CookInfoModel>> getAllClassInfo(String phone) async {
    Database db = await getDataBase();
    List<Map<String, dynamic>> maps =
        await db.rawQuery("select * from $name where $phoneNum = $phone order by $time desc");
    CookInfoModelList cookInfoModelList = CookInfoModelList.fromJson(maps);
    return cookInfoModelList.list;
  }
}
